package com.sghd.candy.utils;

import com.sghd.common.utils.time.DateUtils;

import java.util.Date;

/**
 */
public abstract class DateHelper {

	public final static int MILLIS_PER_MINUTE = 60 * 1000;

	public static final int RESET_HOUR = 5;

	/**
	 * 获取上一次执行时间
	 */
	public static Date getPreTime(String cron, Date now) {
		Date next = DateUtils.getNextTime(cron, now);
		Date next2 = DateUtils.getNextTime(cron, next);

		long dis = next2.getTime() - next.getTime();
		next.setTime(next.getTime() - dis);
		return next;
	}

	public static void printlnNextDate(String cron) {
		Date date = DateUtils.getNextTime(cron, new Date());
		Date nextDate = DateUtils.getNextTime(cron, date);

		System.out.println(DateUtils.date2String(date, DateUtils.PATTERN_DATE_TIME));
		System.out.println(DateUtils.date2String(nextDate, DateUtils.PATTERN_DATE_TIME));

		printlnNextTime(cron);
	}

	public static void printlnNextTime(String cron) {
		Date date = DateUtils.getNextTime(cron, new Date());
		Date nextDate = DateUtils.getNextTime(cron, date);

		System.out.println(nextDate.getTime() - date.getTime());
	}

	/**
	 * 能否重置(指定的小时点)
	 * @param date 上一次重置时间
	 * @param hour 需要重置的时刻
	 * @return true为需要重置，false为不需要重置
	 */
	public static boolean canReset(Date date, int hour) {
		if (date == null) {
			return true;
		}
		Date now = new Date();
		// 减去偏移量
		now = DateUtils.addHours(now, -hour);
		date = DateUtils.addHours(date, -hour);
		return !DateUtils.isSameDay(now, date);
	}

	/**
	 * 能否重置(指定的小时点)，默认时间5点
	 * @param date 上一次重置时间
	 * @return true为需要重置，false为不需要重置
	 */
	public static boolean canReset(Date date) {
		return canReset(date, RESET_HOUR);
	}

	/**
	 * 获取今天重置时间
	 */
	public static Date getToDayResetTime(int hour) {
		return DateUtils.addHours(new Date(), hour);
	}

	/**
	 * 获取今天重置时间
	 */
	public static Date getToDayResetTime() {
		return DateUtils.addHours(new Date(), -RESET_HOUR);
	}

	/** 获取偏移周 索引从1开始 */
	public static int getOffSetWeek(Date date) {
		int result = (int) Math.ceil((DateUtils.calcIntervalDays(date, new Date()) + 1) / 7d);
		if (result == 0) {
			result = 1;
		}
		return result;
	}

	/**
	 * 获取最大日期
	 */
	public static Date max(Date... dates) {
		Date result = null;
		for (Date d : dates) {
			if (d == null) {
				continue;
			}
			if (result == null || result.before(d)) {
				result = d;
			}
		}
		return result;
	}

	/**
	 * 获取最小日期
	 */
	public static Date mix(Date... dates) {
		Date result = null;
		for (Date d : dates) {
			if (d == null) {
				continue;
			}
			if (result == null || result.after(d)) {
				result = d;
			}
		}
		return result;
	}
}
